import { BufferAttribute, BufferGeometry, Material, Mesh} from "three";
import { CqkjMap } from "../Basic/CqkjMap";
import { MapElement, MapElementOption } from "../Basic/MapElement";
import { setValue } from "../Util/common";
import { PROJECTION } from "../Util/static";

export interface SpaceHorizontalProfileOption extends MapElementOption {
  material: Material
  heights: number[]
}

const left = -1669792.361899104
// const left = -4000000.361899104
const right = 2226389.8158654724
const top = 2117971.6426876914
const bottom = -1814349.7038964818

export class SpaceHorizontalProfile extends MapElement<SpaceHorizontalProfileOption>{
  mesh: Mesh<BufferGeometry, Material>;
  get show(): boolean {
    return this.option.show
  }
  set show(val: boolean) {
    setValue(this.option,'show',val,()=>{
      this.mesh.visible=val
    })
  }

  get heights() {
    return this.option.heights
  }

  set heights(val) {
    setValue(this.option, 'heights', val, () => {
      const geometry=this.mesh.geometry
      this.mesh.geometry=createGeometry(val)
      geometry.dispose()
    })
  }

  constructor(map: CqkjMap, option: SpaceHorizontalProfileOption) {
    super(map, option)
    this.mesh = new Mesh(createGeometry(option.heights),option.material)
    map.scene.add(this.mesh)
  }

  onDestroy(): void {
    throw new Error("Method not implemented.");
  }

}


function createGeometry(heights: number[]) {
  const position: number[] = []
  const index: number[] = []
  heights.forEach((e, i) => {
    const i4 = i * 4
    const z = PROJECTION.altToZ(e)
    position.push(
      left, bottom, z,
      right, bottom, z,
      left, top, z,
      right, top, z
    )
    index.push(i4 + 0, i4 + 1, i4 + 2, i4 + 1, i4 + 3, i4 + 2)
  })
  const geometry = new BufferGeometry()
  geometry.attributes.position = new BufferAttribute(new Float32Array(position), 3)
  geometry.index = new BufferAttribute(new Uint16Array(index), 1)
  return geometry

}